import type { TRoute } from '~comp/breadcrumb/Breadcrumb.vue';
import type { MaybeRefOrGetter, Ref } from 'vue';

export type TGameInfo = NonNullable<ReturnType<typeof normalizeGameInfo>>;

/** 规范化游戏信息 */
export function normalizeGameInfo(gameInfo: Api.GetData<typeof apis.apiGameDetail> | undefined) {
  if (gameInfo) {
    return {
      ...gameInfo,
      self: gameInfo.provider_id === 1,
      sport: gameInfo.provider_id === 7,
    };
  }

  return null;
}

/** 跳转到 Play 页 */
export function toPlayPage(game: any) {
  const info = normalizeGameInfo(game);

  if (info)
    return appValues.router?.push({ name: info?.sport ? RN.SPORTS : RN.PLAY, params: { gameCode: game.code } });
  return Promise.reject(new Error('game null'));
}

/** 获取游戏信息 */
export async function getGameInfo(gameCode: string) {
  const detail = await queryClient.fetchQuery({
    queryKey: [apis.apiGameDetail.id, gameCode],
    queryFn: () => apis.apiGameDetail({ code: gameCode }, { errorMessage: false }),
    staleTime: 5000,
  }).catch(() => null);

  return normalizeGameInfo(detail);
}

/** 获取游戏信息 */
export function useGameInfoQuery(gameCode: MaybeRefOrGetter<string>) {
  const gameCodeR = toRef(gameCode);
  const gameInfoQry = useQuery({
    staleTime: 5000,
    queryKey: [apis.apiGameDetail.id, 'game-info', gameCodeR],
    queryFn: () => getGameInfo(gameCodeR.value),
  });
  const gameInfo = computed(() => gameInfoQry.data.value);

  return { gameInfoQry, gameInfo };
}

/** 基于游戏信息得到游戏的面包屑导航 */
export function useGameBreadcrumb(gameCode: Ref<string>) {
  const { gameInfo } = useGameInfoQuery(gameCode);
  return computed(() => {
    const detail = gameInfo.value;
    const typeDetail = detail?.game_type_detail;
    const routes: TRoute[] = [];

    if (!detail)
      return routes;

    if (typeDetail) {
      routes.push([typeDetail.name, buildGameListRoute({ alias: typeDetail.alias })]);
    }

    routes.push([detail.ename]);

    return routes;
  });
}

/** 收藏游戏 */
export function useFavorite(gameCode: MaybeRefOrGetter<string>) {
  const isAuthed = useAuthed();
  const { gameInfo } = useGameInfoQuery(gameCode);
  const favorite = ref(false);
  const likeMut = useMutation({
    mutationKey: [apis.apiGameLike.id],
    mutationFn: apis.apiGameLike,
  });

  const toggle = () => {
    if (!isAuthed.value) {
      globalPopups.sign.open();
      return;
    }

    likeMut.mutate({ requestBody: { game_code: toValue(gameCode) } });
    favorite.value = !favorite.value;
  };

  watch(gameInfo, (v) => {
    favorite.value = !!v?.is_like;
  }, { immediate: true });

  return reactive({ is: favorite, toggle });
}
